package com.ellricky.baselib.ui.course

import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.View
import com.andr.common.http.callback.BaseCallback
import com.andr.common.ui.adapter.BaseRecyclerAdapter
import com.andr.common.ui.mvp.BasePresenter
import com.andr.common.util.FileUtil
import com.ellricky.baselib.BaseConstant
import com.ellricky.baselib.R
import com.ellricky.baselib.adapter.course.PrepareCourseAdapter
import com.ellricky.baselib.cache.LocalCacheUtil
import com.ellricky.baselib.entity.new.PrepareCourse
import com.ellricky.baselib.entity.new.PrepareImg
import com.ellricky.baselib.http.HttpUtils
import com.ellricky.baselib.listener.OnTakePhotoListener
import com.ellricky.baselib.ui.base.BaseRefreshActivity
import com.ellricky.baselib.util.EAppUtil
import com.ellricky.baselib.util.EDialogUtil
import com.ellricky.baselib.util.NewEBaseCallback
import com.ellricky.baselib.util.NewECallback
import com.ellricky.baselib.util.photo.TakePhotoUtil
import org.devio.takephoto.app.TakePhoto
import org.devio.takephoto.app.TakePhoto.TakeResultListener
import org.devio.takephoto.app.TakePhotoImpl
import org.devio.takephoto.model.InvokeParam
import org.devio.takephoto.model.TContextWrap
import org.devio.takephoto.model.TResult
import org.devio.takephoto.permission.InvokeListener
import org.devio.takephoto.permission.PermissionManager
import org.devio.takephoto.permission.PermissionManager.TPermissionType
import org.devio.takephoto.permission.TakePhotoInvocationHandler
import java.io.File

class PrepareCourseActivity : BaseRefreshActivity<Void, BasePresenter<Void>, PrepareImg>(),
    TakeResultListener, InvokeListener, OnTakePhotoListener {

    private val id: String by lazy {
        intent.getStringExtra(BaseConstant.KEY_ID) ?: ""
    }

    private var takePhoto: TakePhoto? = null
    private var invokeParam: InvokeParam? = null
    private var imageUri: Uri? = null

    override fun getResponseCallback(): BaseCallback? {
        return null
    }

    override fun initUIView() {
        super.initUIView()
        mTvTitle.text = "查看文件"
        mBtnRight.text = "添加照片"
        mBtnRight.visibility = View.VISIBLE
    }

    override fun setRefreshListener() {
        rvView.init(this,2)
    }

    override fun onClickBtnRight() {
        super.onClickBtnRight()
        // 添加图片
        EDialogUtil.showTakePhotoDialog(this) { dialogInterface,
                                                item ->
            dialogInterface.dismiss()
            createImageUri()
            TakePhotoUtil.configTakePhotoOption(takePhoto)
            TakePhotoUtil.configCompress(takePhoto)

            if (item == 0) {
                // 拍照
                TakePhotoUtil.takeCamera(takePhoto, null, imageUri)
            } else if (item == 1) {
                TakePhotoUtil.takePicOne(takePhoto, null, imageUri)
            }
        }
    }

    private fun createImageUri() {
        var file = FileUtil.getFileDirE(this, Environment.DIRECTORY_PICTURES)
        val fileName = System.currentTimeMillis().toString() + ".jpg"
        file = File(file, fileName)
        if (!file.parentFile.exists()) {
            file.parentFile.mkdirs()
        }
        imageUri = Uri.fromFile(file)
    }

    override fun getResponseCallback2(): NewEBaseCallback {
        return object : NewECallback<PrepareCourse>(this, false) {
            override fun onSuccess(data: PrepareCourse, msg: String?) {
                dataSource = data.prepare_img
                rvView.onLoadFinish(dataSource, true)
            }
        }
    }

    override fun initParamMap() {
        super.initParamMap()
        paramMap["action"] = "teacherWarePerpareDetail"
        paramMap["ware_id"] = id
        paramMap["school_id"] = LocalCacheUtil.getSchoolId()
        paramMap["eid"] = LocalCacheUtil.getUid()
    }

    override fun getRvAdapter(): BaseRecyclerAdapter<PrepareImg> {
        return PrepareCourseAdapter()
    }

    override fun getUrlPath(): String {
        return ""
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        getTakePhoto()?.onCreate(savedInstanceState)
        super.onCreate(savedInstanceState)
    }


    override fun onSaveInstanceState(outState: Bundle) {
        getTakePhoto()?.onSaveInstanceState(outState)
        super.onSaveInstanceState(outState)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        getTakePhoto()?.onActivityResult(requestCode, resultCode, data)
        super.onActivityResult(requestCode, resultCode, data)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions!!, grantResults!!)
        val type =
            PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults)
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this)
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    private fun getTakePhoto(): TakePhoto? {
        if (takePhoto == null) {
            takePhoto =
                TakePhotoInvocationHandler.of(this).bind(TakePhotoImpl(this, this)) as TakePhoto
        }
        return takePhoto
    }

    override fun takeSuccess(result: TResult) {
        val path = com.ellricky.baselib.util.FileUtil.fileToBase64(result.image?.originalPath ?: "")
        val url = EAppUtil.getApiHost()

        val params = hashMapOf<String, String>(
            "action" to "teacherWarePrepare",
            "ware_id" to id,
            "eid" to LocalCacheUtil.getUid(),
            "prepare_img" to path
        )

        HttpUtils.getInstance().postFrom(url, params,
            object : NewECallback<Any>(this) {
                override fun onSuccess(data: Any?, msg: String?) {
                    loadDataOnInit()
                }
            })
    }

    override fun takeFail(result: TResult?, msg: String) {
        Log.i("TAKE", "takeFail:$msg")
    }

    override fun takeCancel() {
        Log.i("TAKE", resources.getString(R.string.msg_operation_canceled))
    }

    override fun invoke(invokeParam: InvokeParam?): TPermissionType {
        val type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam!!.method)
        if (TPermissionType.WAIT == type) {
            this.invokeParam = invokeParam
        }
        return type
    }

    override fun onClickItem(dialogInterface: DialogInterface?, item: Int) {
        createImageUri()
        TakePhotoUtil.configTakePhotoOption(takePhoto)
        TakePhotoUtil.configCompress(takePhoto)

        if (item == 0) {
            // 拍照
            TakePhotoUtil.takeCamera(takePhoto, null, imageUri)
        } else if (item == 1) {
            TakePhotoUtil.takePicOne(takePhoto, null, imageUri)
        }
    }
}